package reflect.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class test3 {
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read("src/reflect/xml/收藏信息.xml");

        //获取根节点
        Element rootElm = doc.getRootElement();

//        List brandList = rootElm.elements("Brand");
//        for(Iterator it=brandList.iterator();it.hasNext();){
//            Element brand = (Element) it.next();
//            for(Iterator iterator=brand.elementIterator();iterator.hasNext();){
//                Element type = (Element) iterator.next();
//                System.out.println("手机："+brand.attribute("name").getText()+"\t"+type.attribute("name").getText());
//            }
//        }

        //新增
//        Element brand = rootElm.addElement("Brand");
//        brand.addAttribute("name","周慧婷");
//      //添加获得子节点
//        Element type = brand.addElement("Type");
//        type.addAttribute("name","周慧婷2");

        //修改
//        List list=rootElm.elements("Brand");
//        for(Iterator it=list.iterator();it.hasNext();){
//            Element el=(Element)it.next();
//            if(el.attribute("name").getText().equals("周慧婷")){
//                el.addAttribute("name","1111");
//            }
//        }
        //删除
            List list=rootElm.elements("Brand");
            for(Iterator iterator=list.iterator();iterator.hasNext();){
                Element el=(Element)iterator.next();
                if(el.attribute("name").getText().equals("1111")){
                    el.getParent().remove(el);
                }
            }

        //指定编码集
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        //保存文件
        XMLWriter writer =new XMLWriter(new FileWriter("src/reflect/xml/收藏信息.xml"),format);
        writer.write(doc);
        writer.close();
    }
}
